package com.java.springcloud.mybatisplus.conditions.segments;

import com.baomidou.mybatisplus.core.conditions.ISqlSegment;
import com.baomidou.mybatisplus.core.conditions.segments.*;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.java.springcloud.mybatisplus.enums.TdSqlKeyword;
import lombok.AccessLevel;
import lombok.Getter;

import java.util.Arrays;
import java.util.List;

/**
 * 合并 SQL 片段
 *
 * @author zhangtao
 * @since 2018-06-27
 */
@Getter
@SuppressWarnings("serial")
public class TdMergeSegments extends MergeSegments {

    private final IntervalSegmentList interval = new IntervalSegmentList();
    private final SlidingSegmentList sliding = new SlidingSegmentList();
    private final FillSegmentList fill = new FillSegmentList();
    private final GroupBySegmentList groupBy = new GroupBySegmentList();
    private final HavingSegmentList having = new HavingSegmentList();
    private final OrderBySegmentList orderBy = new OrderBySegmentList();

    @Getter(AccessLevel.NONE)
    private String sqlSegment = StringPool.EMPTY;
    @Getter(AccessLevel.NONE)
    private boolean cacheSqlSegment = false;

    @Override
    public void add(ISqlSegment... iSqlSegments) {
        List<ISqlSegment> list = Arrays.asList(iSqlSegments);
        ISqlSegment firstSqlSegment = list.get(0);
        if (TdSqlKeyword.INTERVAL.getSqlSegment().equals(firstSqlSegment.getSqlSegment())) {
            interval.addAll(list);
        } else if (TdSqlKeyword.SLIDING.getSqlSegment().equals(firstSqlSegment.getSqlSegment())) {
            sliding.addAll(list);
        } else if (TdSqlKeyword.FILL.getSqlSegment().equals(firstSqlSegment.getSqlSegment())) {
            fill.addAll(list);
        } else if (MatchSegment.ORDER_BY.match(firstSqlSegment)) {
            orderBy.addAll(list);
        } else if (MatchSegment.GROUP_BY.match(firstSqlSegment)) {
            groupBy.addAll(list);
        } else if (MatchSegment.HAVING.match(firstSqlSegment)) {
            having.addAll(list);
        } else {
            super.add(iSqlSegments);
        }
    }

    @Override
    public String getSqlSegment() {
        if (cacheSqlSegment) {
            return sqlSegment;
        }
        cacheSqlSegment = true;

        sqlSegment = super.getSqlSegment() + interval.getSqlSegment() + sliding.getSqlSegment() + fill.getSqlSegment()
                + groupBy.getSqlSegment() + having.getSqlSegment() + orderBy.getSqlSegment();
        return sqlSegment;
    }
}
